package com.tomcat.utils;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.lang.reflect.Method;

/**
 * 自定义类加载器
 *
 * @author tengfei wang
 * @version 1.0
 * @date Created in 2020/10/1
 */
public class MyClassLoader extends ClassLoader {

    protected Class<?> findClass(String module, String name) {
        String myPath = module + name.replace(".", "/") + ".class";
        System.out.println(myPath);
        byte[] cLassBytes = null;
        FileInputStream fileInputStream = null;
        ByteArrayOutputStream out = null;
        try {
            File file = new File(myPath);
            if (file.exists()) {
                fileInputStream = new FileInputStream(file);
                out = new ByteArrayOutputStream();
                int i = 0;
                while ((i = fileInputStream.read()) != -1) {
                    out.write(i);
                }
                cLassBytes = out.toByteArray();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (fileInputStream != null) {
                    fileInputStream.close();
                }
                if (out != null) {
                    out.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return defineClass(name, cLassBytes, 0, cLassBytes.length);
    }

    public static void main(String[] args) throws Exception {
        MyClassLoader myClassLoader = new MyClassLoader();
        Class<?> aClass = myClassLoader.findClass("demo/","DemoServlet");
        Object o = aClass.newInstance();
        Method[] methods = aClass.getMethods();
        for (Method method : methods) {
            if (method.getName().equalsIgnoreCase("service")) {
                System.out.println(method.getName());
            }
        }
    }
}
